<?php

namespace app\common\service;


use app\common\controller\Smscm;
use app\common\helper\FormatHelper;
use think\Db;
use think\Exception;

/**
 * 房间单据服务
 *
 * Class RoomCheckOutService
 * @package app\common\service
 */
class RoomCheckOutService {

    /**
     * 处理次卡消费
     * @param $data [会员卡消费数据]
     * @param $checkOutID [结账单据ID]
     */
    public static function payNumberCard($data, $checkOutID)
    {
        //查询会员次卡信息
        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id', $data['id'])
            ->find();
        foreach ($data['template_data'] as $key => $value) {
            $number = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id' => $value['template_id']])->value('number');
            $userUseNumber = Db::name('qt_viper_card_use_log')->where(['card_type' => '1', 'viper_card_id' => $data['id'], 'template_id' => $value['template_id']])->sum('number');
            $userUseNumber = intval($userUseNumber);
            if (($userUseNumber + 1) > $number) {
                return FormatHelper::fReturn('会员卡超出使用数量','',FormatHelper::ERROR);
            }
            $product = explode('-', $value['product_id']);
            if ($product[0] == '1') {
                //项目
                $itemPrice = Db::name('qt_project')->where(['id' => $product[1]])->value('price');
            } else {
                //项目
                $itemPrice = Db::name('qt_goods')->where(['id' => $product[1]])->value('price');
            }
            //插入会员卡使用记录
            $insert = [
                'user_id' => $viperUser['id'],
                'store_id' => $viperUser['store_id'],
                'viper_card_id' => $data['id'],
                'template_id' => $value['template_id'],
                'order_id' => $checkOutID,
                'item_type' => $product[0],
                'item_id' => $product[1],
                'item_price' => $itemPrice,
                'number' => $value['num'],
                'create_time' => time(),
                'card_type' => '1',
                'card_item_id' => $value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
            //更新会员卡次卡使用次数
            Db::name('qt_viper_card_item')->where(['id' => $value['card_item_id']])->setInc('use_number', '1');

        }
        //更新会员最后消费时间
        Db::name('qt_viper_card')->where('id', $viperUser['id'])->update(['end_consumption_time' => time()]);

    }

    /**
     * 处理月卡消费
     * @param $data
     */
    public static function payMonthCard($data, $checkOutID)
    {
        //查询会员月卡信息
        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id', $data['id'])
            ->find();
        foreach ($data['template_data'] as $key => $value) {
            $template = Db::name('qt_viper_month_card_template')->where('id', $value['template_id'])->find();
            $userMonthStatus = Db::name('qt_viper_card_item')
                ->where(['viper_card_id' => $value['id'], 'month_template_id' => $value['template_id'], 'status' => '1'])
                ->find();
            if (empty($userMonthStatus)) {

                return FormatHelper::fReturn('该月卡已经禁止使用','',FormatHelper::ERROR);
            }
            if ($template['type'] == '1') {
                //每天
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'today')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    return FormatHelper::fReturn('会员卡超出使用频率','',FormatHelper::ERROR);
                }
            }
            if ($template['type'] == '2') {
                //每月
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'm')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    return FormatHelper::fReturn('会员卡超出使用频率','',FormatHelper::ERROR);
                }
            }
            if ($template['type'] == '3') {
                //每年
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'y')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    return FormatHelper::fReturn('会员卡超出使用频率','',FormatHelper::ERROR);
                }
            }
            $product = explode('-', $value['product_id']);
            if ($product[0] == '1') {
                //项目
                $itemPrice = Db::name('qt_project')->where(['id' => $product[1]])->value('price');
            } else {
                //项目
                $itemPrice = Db::name('qt_goods')->where(['id' => $product[1]])->value('price');
            }
            //插入会员卡使用记录
            $insert = [
                'user_id' => $viperUser['id'],
                'store_id' => $viperUser['store_id'],
                'viper_card_id' => $data['id'],
                'template_id' => $value['template_id'],
                'order_id' => $checkOutID,
                'item_type' => $product[0],
                'item_id' => $product[1],
                'item_price' => $itemPrice,
                'number' => $value['num'],
                'create_time' => time(),
                'card_type' => '2',
                'card_item_id' => $value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
            //更新会员卡次卡使用次数
            Db::name('qt_viper_card_item')->where(['id' => $value['card_item_id']])->setInc('use_number', '1');
        }
        //更新会员最后消费时间
        Db::name('qt_viper_card')->where('id', $viperUser['id'])->update(['end_consumption_time' => time()]);


    }

    /**
     * 会员卡支付
     * @param $data
     */
    public static function payCard($data, $checkOutId,$userInfo,$charge_recovery = 0)
    {
        $viperCard = Db::name('qt_viper_card')->where(['id' => $data['id']])->find();
        //会员卡输入密码
        $storeInfo = Db::name('qt_store')->where(['id' => $viperCard['store_id']])->find();
        //仅密码支付
        if ($storeInfo['viper_pay_verify_type'] == '2') {
            if ($storeInfo['is_viper_passwd_input'] == '1') {
                //判断密码是否是默认的
                $defaultPass = pwd(config('default_passwd'), $viperCard['salt']);
                if ($defaultPass != $viperCard['passwd']) {
                    //判断密码是否正确
                    $pass = pwd($data['passwd'], $viperCard['salt']);
                    if ($pass != $viperCard['passwd']) {
                        return FormatHelper::fReturn('密码错误','',FormatHelper::ERROR);
                    }
                }
            }
        }
        //仅验证码支付
        if ($storeInfo['viper_pay_verify_type'] == '1') {
            $code = $data['code'];
            $sms = new Smscm();
            $status = $sms->check_smscode($viperCard['mobile'], $code, '3');
            if ($status['code'] != '200') {
                return FormatHelper::fReturn('验证码错误','',FormatHelper::ERROR);
            }
        }
        //验证码加密码
        if ($storeInfo['viper_pay_verify_type'] == '3') {
            if ($storeInfo['is_viper_passwd_input'] == '1') {
                //判断密码是否是默认的
                $defaultPass = pwd(config('default_passwd'), $viperCard['salt']);
                if ($defaultPass != $viperCard['passwd']) {
                    //判断密码是否正确
                    $pass = pwd($data['passwd'], $viperCard['salt']);
                    if ($pass != $viperCard['passwd']) {
                        return FormatHelper::fReturn('密码错误','',FormatHelper::ERROR);
                    }
                }
                $code = $data['code'];
                $sms = new Smscm();
                $status = $sms->check_smscode($viperCard['mobile'], $code, '3');
                if ($status['code'] != '200') {
                    return FormatHelper::fReturn('验证码错误','',FormatHelper::ERROR);
                }
            }
        }
        //验证码加自设密码
        if ($storeInfo['viper_pay_verify_type'] == '4') {
            //判断密码是否正确
            $pass = pwd($data['passwd'], $viperCard['salt']);
            if ($pass != $viperCard['passwd']) {
                return FormatHelper::fReturn('密码错误','',FormatHelper::ERROR);
            }
            $code = $data['code'];
            $sms = new Smscm();
            $status = $sms->check_smscode($viperCard['phone'], $code, '3');
            if ($status['code'] != '200') {
                return FormatHelper::fReturn('验证码错误','',FormatHelper::ERROR);
            }
        }
        if (empty($viperCard)) {
            return FormatHelper::fReturn('暂未找到该会员卡','',FormatHelper::ERROR);
        }
        if ($viperCard['amount'] < $data['pay_amount']) {
            return FormatHelper::fReturn('会员卡余额不足','',FormatHelper::ERROR);
        }
        if ($viperCard['give_amount'] < $data['pay_give_amount']) {
            return FormatHelper::fReturn('会员卡赠送余额不足','',FormatHelper::ERROR);
        }
        if ($viperCard['status']  == '2' || $viperCard['status'] == '3' || $viperCard['status'] == '4') {
            return FormatHelper::fReturn('会员卡已经挂失','',FormatHelper::ERROR);
        }
        //查找会员
        try {
            //更新会员
            //Db::name('qt_user_viper')->where('id', $viperUser['id'])->setDec('money', $data['pay_amount']);
            //更新余额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setDec('amount', $data['pay_amount']);
            //更新赠送余额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setDec('give_amount', $data['pay_give_amount']);
            //更新消费金额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setInc('consumption_amount', ($data['pay_amount'] + $data['pay_give_amount']));
            //更新会员最后消费时间
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->update(['end_consumption_time' => time()]);
            //插入会员消费记录
            $after = $viperCard['amount'] - $data['pay_amount'];
            $afterGive = $viperCard['give_amount'] - $data['pay_give_amount'];
            $log[0] = [
                'viper_card_id' => $viperCard['id'],
                'order_id' => $checkOutId,
                'type' => '3',
                'money' => $data['pay_amount'],
                'create_time' => time(),
                'content' => '',
                'check' => '2',
                'flag' => '1',
                'after_money' => $after,
            ];
            if (!empty($data['pay_give_amount'])) {
                $log[1] = [
                    'viper_card_id' => $viperCard['id'],
                    'type' => '3',
                    'order_id' => $checkOutId,
                    'money' => $data['pay_give_amount'],
                    'create_time' => time(),
                    'content' => '',
                    'check' => '2',
                    'flag' => '3',
                    'after_money' => $afterGive,
                ];
            }
            Db::name('qt_viper_money_log')->insertAll($log);
            check_out_card_pay_all($viperCard['id'],($data['pay_amount'] + $data['pay_give_amount']), $checkOutId, $userInfo, '2', $data['pay_amount'],$data['pay_give_amount'],$after,$afterGive,$charge_recovery);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            return FormatHelper::fReturn('消费失败','',FormatHelper::ERROR);
        }
    }


}
